import machine
import uos, pyb
import micropython
import rtc_wake
import pwsutil

# 启动watchdog，确保在指定时间内完成前导任务

micropython.alloc_emergency_exception_buf(100)

pyb.country('US')

main = ''
rtc_wake.wake = False

wdtenable = pyb.Pin('A1', pyb.Pin.IN, pyb.Pin.PULL_UP).value()

if (wdtenable):
	pwsutil.wdt_start()

def checkMain():
	mainfile = ''
	mainfolder = ''
	try:
		running = open('/data/running', 'r')
		mainfolder = running.read(1)
		running.close()
		
		if (mainfolder in ('a', 'b')):
			mainfile = '/data/' + mainfolder + '/main.py'
	except:
		mainfile = '/flash/main.py'

	return mainfile

def checkFault():
	oncefile = '/data/first'
	faultfile = '/data/fault'
	try:
		uos.stat(oncefile)
		uos.rename(oncefile, faultfile)
		return False
	except:
		onecefile = ''
	
	try:
		uos.stat(faultfile)      #让紧急升级程序来清理
		return True
	except:
		faultfile = ''
	
	return False

try:
	p2 = pyb.Flash(start=256*1024)
	uos.mount(p2, '/data')
except:
	uos.VfsLfs2.mkfs(p2)
	uos.mount(p2, '/data')
	main = '/flash/main.py'    # 默认主文件，不断读取升级固件

if (main == ''):
	# 判断data文件系统下的主文件是否正常
	main = checkMain()
	
# 判断是否是升级后首次运行，如果不是，则默认进入紧急升级状态
if checkFault():
	# 判断有没有上个正常版本
	try:
		uos.remove('/data/running')
		uos.remove('/data/fault')
		uos.stat('/data/running.bak')
		uos.rename('/data/running.bak', '/data/running')
		main = checkMain()
	except:
		main = '/flash/main.py'
# 判断backup sram 1有没有接收到Agent的确认。如果没有，则进入紧急升级状态
if (pwsutil.readBKSRAM(1) == 0):
	main = '/flash/main.py'
else:
	pwsutil.writeBKSRAM(1, 0)

last_check = 0

def rtc_callback(t):
	global last_check

	rtc_wake.wake = True
	pwsutil.wdt_feed()
	pwsutil.time_count += 1
	if ((pwsutil.time_count - last_check) > 1800):
		last_check = pwsutil.time_count
		if (pwsutil.readBKSRAM(1) == 0):
			pyb.hard_reset()
		else:
			pwsutil.writeBKSRAM(1, 0)


pyb.RTC().wakeup(2000, rtc_callback)

uos.chdir(main[:-8])
pyb.main(main)

